<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">人脸识别校园后台管理系统</h3>
      </div>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="用户管理" name="first">
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="登录账号"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
              onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"
            />
          </el-form-item>

          <el-tooltip
            v-model="capsTooltip"
            content="Caps lock is On"
            placement="right"
            manual
          >
            <el-form-item prop="password">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="登录密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>
          </el-tooltip>

          <el-button
            :loading="loading"
            type="primary"
            style="width: 100%; margin-bottom: 30px"
            @click.native.prevent="handleLogin"
            >账号密码登录</el-button
          >

          <!--canvas截取流-->
          <canvas
            style="display: none"
            ref="canvas"
            width="640"
            height="480"
          ></canvas>

          <el-button
            :loading="loading"
            type="primary"
            style="width: 100%; margin-bottom: 30px"
            @click.native.prevent="startRecognize"
            >人脸识别登录</el-button
          >
        </el-tab-pane>

        <el-tab-pane label="用户注册" name="second">
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="username"
              v-model="registForm.username"
              placeholder="登录账号"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
              onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"
            />
          </el-form-item>
          <el-form-item prop="realname">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="realname"
              v-model="registForm.realname"
              placeholder="真实姓名"
              name="realname"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>
          <el-tooltip
            v-model="capsTooltip"
            content="Caps lock is On"
            placement="right"
            manual
          >
            <el-form-item prop="password">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="registForm.password"
                :type="passwordType"
                placeholder="登录密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="submitRegist"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>
          </el-tooltip>

          <el-form-item prop="gender">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-select
              style="width: 85%"
              v-model="registForm.gender"
              placeholder="性别"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-button
            :loading="loading"
            type="primary"
            style="width: 100%; margin-bottom: 30px"
            @click.native.prevent="submitRegist"
            >人脸注册</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <el-dialog
      top="6vh"
      title="人脸识别区域"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="closeDialog"
    >
      <el-row type="flex" justify="center">
        <el-col :span="24">
          <div id="contentHolder">
            <video id="video" width="100%" autoplay ref="videos"></video>
          </div>

          <el-button
            v-if="isRegist"
            type="primary"
            @click="chooseImage()"
            size="mini"
            >确定选取人脸</el-button
          >
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { aiLogin, aiRegist, checkAiLogin } from "@/api/user.js";

export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (validUsername(value)) {
        callback(new Error("请输入 用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (validUsername(value)) {
        callback(new Error("请输入 密码"));
      } else if (value.length < 6) {
        callback(new Error("密码长度大于6位"));
      } else {
        callback();
      }
    };
    return {
      options: [
        {
          value: "0",
          label: "男",
        },
        {
          value: "1",
          label: "女",
        },
      ],

      isRegist: false,
      activeName: "first",
      dialogVisible: false,
      form: {
        username: "",
        password: "",
      },

      timer: {},
      aiLoginReq: {},
      headImgSrc: "",
      active: "1",
      loginForm: {
        username: "",
        password: "",
      },
      registForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    chooseImage() {
      console.log("choose");

      this.photograph();
    },
    handleClick(tab, event) {
      if (tab.index == 1) {
        this.isRegist = true;
      } else if (tab.index == 0) {
        this.isRegist = false;
      }
    },

    submitRegist() {
      this.isRegist = true;
      if (
        this.registForm.username != null &&
        this.registForm.username != "" &&
        this.registForm.password != null &&
        this.registForm.password != ""
      ) {
        checkAiLogin(this.registForm).then((response) => {
          console.log("");
          if (response.code == 200 && response.msg === "exist") {
            this.$message({ message: "账号已经存在!!", type: "warning" });
          } else {
            this.startRecognize();
          }
        });
      } else {
        this.$message({
          message: "请填写基本信息!!",
          type: "warning",
        });
      }
    },

    closeDialog() {
      this.dialogVisible = false;
      this.endRecognize();
      clearInterval(this.timer);
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },

    photograph() {
      let ctx = this.$refs["canvas"].getContext("2d");
      // 把当前视频帧内容渲染到canvas上
      ctx.drawImage(this.$refs.videos, 0, 0, 640, 480);
      // 转base64格式、图片格式转换、图片质量压缩
      let imgBase64 = this.$refs["canvas"].toDataURL("image/jpeg", 0.7); // 由字节转换为KB 判断大小

      let str = imgBase64.replace("data:image/jpeg;base64,", "");
      let strLength = str.length;
      let fileLength = parseInt(strLength - (strLength / 8) * 2); // 图片尺寸  用于判断
      this.aiLoginReq.base64ImageStr = str;
      let _this = this;
      if (this.isRegist) {
        this.registForm.imgBase64 = str;
        aiRegist(this.registForm).then((response) => {
          if (response.code == 200) {
            this.dialogVisible = false;
            this.endRecognize();
            this.isRegist = false;
            this.activeName = "first";
            this.$message({ message: "注册成功 请登录", type: "success" });
          }
        });
        console.log(" 去注册");
      } else {
        aiLogin(this.aiLoginReq).then((response) => {
          console.log(response);
          if (response.code == 200 && response.data != null) {
            //关闭摄像头
            this.endRecognize();
            //关闭定时提交登录请求任务
            clearInterval(this.timer);
            this.loginForm.username = response.data.username;
            this.loginForm.password = response.data.password;
            this.$message({ message: "人脸识别成功", type: "success" });
            this.handleLogin();
          } else if (response.code == 401) {
            this.$message({ message: "不存在该用户 请注册", type: "warning" });
            this.closeDialog();
            this.activeName = "second";
          } else {
            this.$message({
              message: "人脸登录失败,请将人脸对准识别区域",
              type: "warning",
            });
          }
        });
      }
    },

    endRecognize() {
      if (!this.$refs.videos.srcObject) {
        this.dialogCamera = false;
        return;
      }
      let stream = this.$refs.videos.srcObject;
      let tracks = stream.getTracks();
      tracks.forEach((track) => {
        track.stop();
      });
      this.$refs.videos.srcObject = null;
    },
    //创建扫描控件
    startRecognize() {
      this.dialogVisible = true;

      let _this = this;
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices
          .getUserMedia({
            video: true,
          })
          .then(function (stream) {
            // 摄像头开启成功
            _this.$refs.videos["srcObject"] = stream;
            //_this.$refs['video'].srcObject = stream
            // 实时拍照效果
            _this.$refs.videos.play();
            // _this.MediaStreamTrack =
            //   typeof stream.stop === "function"
            //     ? stream
            //     : stream.getTracks()[1];
            // var video = _this.$refs.videos;
            // video["srcObject"] = stream;
            // video.play();
          })
          .catch(function (err) {
            console.log(err);
          });
      }
      if (!this.isRegist) {
        this.timer = setInterval(this.photograph, 3000);
      }
      //
    },

    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then((response) => {
              if (response.code === 40000) {
                //当登录的用户名密码错误的时候 会返回 40000 并且不会被 request的 response拦截器拦截，直接过来 到这里拦截
                this.$message({ message: response.msg, type: "warning" });
              } else {
                this.$router.push({
                  path: this.redirect || "/",
                  query: this.otherQuery,
                });
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
